<?php
$this_dir = dirname(__FILE__) . '/';
require_once($this_dir . '../plugin/autoload.php');

$uri = $_SERVER['REQUEST_URI'];
$conf = new ConfLib();
$rules = $conf->get('route', 'controller');
$controller_name = '';

function route($rules, $uri) {
    foreach($rules as $k=>$v) {
        if(1 === preg_match('/' . $k . '/', $uri)) {
            return $v;
        }
    }
    throw new Exception();
}

$controller_name = route($rules, $uri);

$c = new $controller_name ($uri);
$r = $c->route();
function getStatusStr($code) {
    //fastcgi与apache module不同
    //这里按照fastcgi格式
    //http://cn.php.net/manual/en/function.header.php
    $http_code_map = array(
        '200' => '200 OK',
        '202' => '202 Accepted',
        '301' => '301 Moved Permanently',
        '302' => '302 Found',
        '404' => '404 Not Found',
    );
    return 'Status: ' . $http_code_map[$code];
}
function output($r) {
    //fastcgi与apache module不同
    //这里按照fastcgi格式
    //http://cn.php.net/manual/en/function.header.php
    $status_str = getStatusStr($r['http']['status_code']);
    if(in_array($r['http']['status_code'], array(301, 302))) {
        header('Location: ' . $r['http']['uri'], true, $r['http']['status_code']);
        exit;
    } else {
        if(in_array($r['http']['status_code'], array(202, 404))) {
            if(isset($r['http']['uri'])) {
                header('Location: ' . $r['http']['uri'], true, $r['http']['status_code']);
                exit;
            } else {
                if(empty($r['tpl'])) {
                    header($status_str);
                    echo $status_str;
                    exit;
                }
            }
        } else {
            header($status_str);
        }
    }
    $v = $r['data'];
    header('Content-Type: ' . $r['http']['content-type']);
    switch($r['http']['content-type']) {
        case 'text/html' :
            $conf = new ConfLib();
            $v['static_uri'] = $conf->get('static', 'uri');
            require dirname(__FILE__) . '/../view/default/'. $r['tpl'] . '.tpl';
            break;
        case 'text/plain' :
            echo $v;
            break;
        case 'application/json' :
            echo json_encode($v);
            break;
        case 'application/atom+xml' :
            //todo
            break;
    }
    return true;
}
output($r);
exit;
?>
